package com.itheima.web;

import com.itheima.Service.UserService;
import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @GetMapping("/sendCode/{phone}")
    public R sendValidateCode(@PathVariable String phone, HttpSession session) {

        String code = ValidateCodeUtils.generateValidateCode4String(4);
        System.out.println("验证码：" + code);

        session.setAttribute(phone, code);

        return R.success(code);

    }

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String code = map.get("code");
//        System.out.println("phone = " + phone);
//        System.out.println("code = " + code);
        String validateCode = (String) session.getAttribute(phone);
        if (validateCode != null && validateCode.equalsIgnoreCase(code)) {

            User user = userService.findUser(phone);

            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setName(phone);
                int row = userService.add(user);
                if (row > 0) {
                    session.setAttribute("user", user);
                    return R.success("登录成功");
                }
                return R.error("登录失败");
            } else {
                session.setAttribute("user", user);
                return R.success("登录成功");
            }
        }
        return R.error("登录失败");
    }
}
